package cn.swu.ws.user;
import cn.swu.ws.dao.MysqlDbDao;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Objects;

@WebServlet("/EnrollServlet")
public class EnrollServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Connection connection;
        try {
            connection = MysqlDbDao.login_database();
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
        Statement statement;
        try {
            statement = connection.createStatement();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        Writer writer = resp.getWriter();
        String template = "{\n" +
                "\t\"repeat\": %d,\n" +
                "\t\"add_user\": %d,\n" +
                "\t\"msg\": \" 注册\",\n" +
                "\t\"data\": null\n" +
                "}";
        String select_sql = "select username,password from user_information;";
        ResultSet rs = null;
        try {
            rs = statement.executeQuery(select_sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        System.out.println(rs);

        while(true) {
            try {
                if (!rs.next()) break;
                String db_name = rs.getString("username");
                String db_password = rs.getString("password");
                System.out.println(db_name);
                System.out.println(db_password);
                if(Objects.equals(db_name, req.getParameter("username"))){
                    String repeat = String.format(template, 1,0);
                    writer.write(repeat);
                    return;
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            // 通过字段检索

        }
        String tem ="INSERT INTO user_information(username,password) VALUES('%s','%s')";
        String sql = String.format(tem, req.getParameter("username"),req.getParameter("password"));
        System.out.println(sql);
        int resultSet = 0;
        try {
            resultSet = statement.executeUpdate(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        System.out.println("成功");
        String add_user_success = String.format(template,0, resultSet);
        writer.write(add_user_success);
    }
}
